from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse

from .models import UserInfo, Address, Area
from .user_verify import verify_user
from utils.get_cap import get_image


def login(request):
    if request.method == 'POST':
        try:
            user = UserInfo.objects.get(username=request.POST.get('account'), password=request.POST.get('password'))
        except UserInfo.DoesNotExist:
            text = '账号或密码错误!'
        else:
            request.session['user_id'], request.session['user'] = user.pk, user.username
            try:
                path = request.session['path']
                del request.session['path']
            except KeyError:
                path = '/'
            return redirect(path)
    return render(request, 'users/user_login.html', locals())


def register(request):
    if request.method == 'POST':
        try:
            UserInfo.objects.get(username=request.POST.get('account'), password=request.POST.get('password'))
        except UserInfo.DoesNotExist:
            user = UserInfo.objects.create(username=request.POST.get('account'), password=request.POST.get('password'))
            request.session['user_id'], request.session['user'], path = user.pk, user.username, request.session['path']
            del request.session['path']
            return redirect(path)
        else:
            text = '用户已经存在'
    return render(request, 'users/register.html', locals())


@verify_user
def user_index(request):
    return render(request, 'users/user_index.html', locals())


def verification_code(request):
    cap, img = get_image()
    request.session['cap'] = cap
    with open(img, 'rb') as f:
        return HttpResponse(f.read(), content_type='image/png')


@verify_user
def address(request):
    if request.method == 'GET':
        user = UserInfo.objects.get(username=request.session.get('user'))
        provinces = Area.objects.filter(p__isnull=True).values('id', 'name')
        addrs = user.address_set.values('a_name', 'pk', 'a_phone', 'addr', 'is_default')
    elif request.method == 'POST':
        UserInfo.objects.get(pk=request.session['user_id']).address_set.update(is_default=False)
        Address.objects.create(
            a_name=request.POST.get('name', ''),
            a_phone=request.POST.get('phone', ''),
            addr=request.POST.get('address', ''),
            is_default=True,
            user_id=request.session['user_id']
        )
        if request.POST.get('type'):
            return HttpResponse('ok')
    return render(request, 'users/address.html', locals())


def check_code(request):
    if request.session.get('cap') == request.GET.get('code', '1').lower():
        return HttpResponse(1)
    return HttpResponse()


def logout(request):
    try:
        del request.session['user'], request.session['user_id']
    except KeyError:
        pass
    if request.GET.get('code'):
        return HttpResponse('OK')
    return redirect('/')


def auto_login(request):
    user = UserInfo.objects.all()[0]
    request.session['user_id'], request.session['user'] = user.pk, user.username
    return redirect('/')


def area(request):
    types = request.POST.get('type')
    data = {}
    if types == '1':
        areas = list(Area.objects.filter(p_id=request.POST.get('provinceId')).values('id', 'name'))
        data['citys'] = areas
        try:
            data['areas'] = list(Area.objects.filter(p_id=areas[0]['id']).values('id', 'name'))
        except IndexError:
            data['areas'] = []
    elif types == '2':
        data['areas'] = list(Area.objects.filter(p_id=request.POST.get('cityId')).values('id', 'name'))
    return JsonResponse(data)
